import xml.etree.ElementTree as ET


# 根据string的name属性查找标签的内容
def find_string_content_by_name(file_path, name):
    """
    根据string标签的内容查找name属性。

    :param file_path: strings.xml文件的路径
    :param name: string标签中的name属性
    :return: 对应的name属性的content，如果未找到则返回None
    """
    tree = ET.parse(file_path)
    root = tree.getroot()

    for string in root.findall('string'):
        if string.get("name", "") == name:
            return string.text

    return None


def find_name_by_string_content(file_path, content):
    """
    根据string标签的内容查找name属性。

    :param file_path: strings.xml文件的路径
    :param content: string标签中的文本内容
    :return: 对应的name属性值，如果未找到则返回None
    """
    tree = ET.parse(file_path)
    root = tree.getroot()

    for string in root.findall('string'):
        if string.text == content:
            return string.get('name')

    return None


def update_string_content(file_path, key, content):
    """
    修改strings.xml文件中某个name属性为key的标签内容为content。

    :param file_path: strings.xml文件的路径
    :param key: 需要修改的string标签的name属性值
    :param content: 新的内容
    """
    tree = ET.parse(file_path)
    root = tree.getroot()

    # 查找name属性为key的string标签
    for string in root.findall('string'):
        if string.get('name') == key:
            string.text = content
            break
    else:
        print(f'No string tag with name attribute "{key}" found.')

    # 将修改后的XML树写回文件
    tree.write(file_path, encoding='utf-8', xml_declaration=True)


def indent(elem, level=0):
    """
    格式化xml
    :param elem: 节点
    :param level: 节点的级别
    """
    i = "\n" + level * "\t"
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "\t"
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i


def insert_translation(file_path, name, value):
    """
    新增string标签
    :param file_path:strings.xml绝对路径
    :param name: name属性
    :param value: 翻译内容
    """
    # 解析 strings.xml 文件
    tree = ET.parse(file_path)
    root = tree.getroot()

    # 检查 <resources> 标签是否存在
    if root.tag != 'resources':
        raise ValueError("The root element is not <resources>")

    # 创建新的 <string> 元素
    new_string = ET.Element('string', {'name': name})
    new_string.text = value

    # 添加缩进
    root.findall('string')[-1].tail = "\n    "

    # 将新元素插入 <resources> 标签下
    root.append(new_string)
    # indent(root)
    new_string.tail = "\n"

    # 将修改后的内容写回文件
    tree.write(file_path, encoding="utf-8", xml_declaration=True)


# 示例：往 strings.xml 文件中插入一行翻译
# demo_file_path = 'C:/root/dev/zk/BodyScale/app/src/main/res/values-en/strings.xml'  # 替换为你的文件路径
# insert_translation(demo_file_path, 'blood_pressure', 'blood pressure')
# insert_translation(demo_file_path, 'tip_test', 'just a test')

# 示例使用
# file_path = 'strings_en.xml'
# key = 'title_balance'
# content = 'new content'
# update_string_content(file_path, key, content)

# 示例使用
# file_path = 'strings_en.xml'
# content = 'BALANCE ASSESSMENT'
# name_attribute = find_name_by_string_content(file_path, content)
# if name_attribute:
#     print(f'Found name attribute: {name_attribute}')
# else:
#     print('Name attribute not found')
